from django.contrib.auth.backends import BaseBackend
from django.db.models import Q
from rest_framework import serializers
from app.models import User

"""
自定义用户登录认证
"""
class MyBackend(BaseBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        try:
            user = User.objects.get(Q(username=username) | Q(mobile=username) | Q(email=username))
        except :
            raise serializers.ValidationError( "未找到改用户！")
        else:
            if user.check_password(password):
                return user
            else:
                # raise serializers.ValidationError({'error': "密码不正确！"})
                raise serializers.ValidationError("密码不正确！")